<template>
    <div class="home">
        <van-nav-bar title="发布文章" left-text="" right-text="发布" @click-left="onClickLeft" @click-right="onClickRight" />

        <div class="publi">
        	<!--<textarea class="text" maxlength="300"  @keydown="listen($event)" v-model="desc" placeholder="写文章......">-->
            <textarea class="text" maxlength="300" @input="descInput" v-model="desc" placeholder="写文章......">
            
                
          </textarea>
            <span class="xianzhi">{{remnant}}/300</span>
        </div>
        {{type}}
        <div class="publit">

            <div class="progress" :style="{backgroundImage:'linear-gradient(to right,#C0C7CB 0%,#C0C7CB '+progress+',#E1E6E9 '+progress+',#E1E6E9 100%)'}"></div>
            <!--<input type="file" name="" id="" value="" />-->
            <van-uploader v-model="fileList" :max-count="maxcount" :before-delete='updelete' :after-read="afterRead" />
            <!--<van-uploader-->
            <!--v-model="fileList"  :max-count="maxcount" :before-delete='updelete' :after-read="afterRead"
      >
        <img
          src="../img/bianzhu2@2x.png"
          alt="等待传图"
          class="imgPreview"
        />
      </van-uploader>-->

        </div>
        <div v-show='isloading' style="width: 100%;height: 100%;position: fixed;background: #F5F5F5;top: 0rem;opacity: .5;"></div>
        <van-loading v-show='isloading' class='back' type="spinner" color="rgba(107, 80, 248, 1)" />

    </div>
</template>

<script>
    // @ is an alias to /src
    //import HelloWorld from '@/components/HelloWorld.vue'

    import Exif from 'exif-js'
    export default {
        name: 'home',
        data() {
            return {
                active: 0,
                value: '',
                remnant: 0,
                desc: '',
                fileList: [],
                testcontent: '',
                images: [],
                maxcount: 3,
                istrue: true,
                filename: '',
                progress: 0,
                currentRate: 0,
                isloading: false,
                type: ''

            }
        },
        computed: {
            text() {
                return this.progress + '%'
            }
        },
        methods: {
            onClickLeft() {
                var ua = navigator.userAgent.toLowerCase();
                if(/iphone|ipad|ipod/.test(ua)) {
                    window.webkit.messageHandlers.onBack.postMessage('');
                } else if(/android/.test(ua)) {
                    if((typeof jsObj) != "undefined") {
                        jsObj.onBack()
                    } else {

                    }
                } else {
                    this.$router.go(-1)
                }
            },
            afterRead(file) {
                
                this.progress = 0
                var that = this;
                this.isloading = true
                this.imgPreview(file.file);
              
                /* 调取接口*/
               /*console.log(that.dataURLtoFile(file.content, file.file.name))
               var params = new FormData()
               params.append('attachment',that.dataURLtoFile(file.content,file.file.name) )          
               that.attach(params)*/   

            },
             /*图片上传压缩*/
            imgPreview(file) {
                let self = this;
                let Orientation;
                //去获取拍照时的信息，解决拍出来的照片旋转问题
                Exif.getData(file, function() {
                    Orientation = Exif.getTag(this, 'Orientation');
                });
                // 看支持不支持FileReader 
                if(!file || !window.FileReader) return;

                if(/^image/.test(file.type)) {
                    // 创建一个reader
                    let reader = new FileReader();
                    // 将图片2将转成 base64 格式
                    reader.readAsDataURL(file);
                    // 读取成功后的回调
                    reader.onloadend = function() {
                        let result = this.result;
                        let img = new Image();
                        img.src = result;                       
                        //判断图片是否大于100K,是就直接上传，反之压缩图片
                        if(this.result.length <= (100 * 1024)) {                           
//                          self.headerImage = this.result;
//                          self.postImg();
//                          let data = self.compress(img, Orientation);                              
//                          self.headerImage = data;
//                          self.postImg();
                            img.onload = function() {                               
                                let data = self.compress(img, Orientation);                               
                                self.headerImage = data;
                                self.postImg();
                            }
                        } else {
                            img.onload = function() {                               
                                let data = self.compress(img, Orientation);                               
                                self.headerImage = data;
                                self.postImg();
                            }
                        }
                    }
                }else{
                   this.isloading = false
                   this.$toast({
                            "message": '格式不正确',
                            'duration': 500
                        }) 
                }
            },
            /*图片旋转*/
            rotateImg(img, direction, canvas) {
                //最小与最大旋转方向，图片旋转4次后回到原方向
                const min_step = 0;
                const max_step = 3;
                if(img == null) return;
                //img的高度和宽度不能在img元素隐藏后获取，否则会出错
                let height = img.height;
                let width = img.width;
                let step = 2;
                if(step == null) {
                    step = min_step;
                }
                if(direction == 'right') {
                    step++;
                    //旋转到原位置，即超过最大值
                    step > max_step && (step = min_step);
                } else {
                    step--;
                    step < min_step && (step = max_step);
                }
                //旋转角度以弧度值为参数
                let degree = step * 90 * Math.PI / 180;
                let ctx = canvas.getContext('2d');
                switch(step) {
                    case 0:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.drawImage(img, 0, 0);
                        break;
                    case 1:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, 0, -height);
                        break;
                    case 2:
                        canvas.width = width;
                        canvas.height = height;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, -height);
                        break;
                    case 3:
                        canvas.width = height;
                        canvas.height = width;
                        ctx.rotate(degree);
                        ctx.drawImage(img, -width, 0);
                        break;
                }
            },
            /*base64压缩*/
            compress(img, Orientation) {
                let canvas = document.createElement("canvas");
                let ctx = canvas.getContext('2d');
                //瓦片canvas
                let tCanvas = document.createElement("canvas");
                let tctx = tCanvas.getContext("2d");
                let initSize = img.src.length;
                let width = img.width;
                let height = img.height;
                //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
                let ratio;
                if((ratio = width * height / 4000000) > 1) {
                    console.log("大于400万像素")
                    ratio = Math.sqrt(ratio);
                    width /= ratio;
                    height /= ratio;
                } else {
                    ratio = 1;
                }
                canvas.width = width;
                canvas.height = height;
                //        铺底色
                ctx.fillStyle = "#fff";
                ctx.fillRect(0, 0, canvas.width, canvas.height);
                //如果图片像素大于100万则使用瓦片绘制
                let count;
                if((count = width * height / 1000000) > 1) {
                    console.log("超过100W像素");
                    count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
                    // 计算每块瓦片的宽和高
                    let nw = ~~(width / count);
                    let nh = ~~(height / count);
                    tCanvas.width = nw;
                    tCanvas.height = nh;
                    for(let i = 0; i < count; i++) {
                        for(let j = 0; j < count; j++) {
                            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                        }
                    }
                } else {
                    ctx.drawImage(img, 0, 0, width, height);
                }
                //修复ios上传图片的时候 被旋转的问题
                if(Orientation != "" && Orientation != 1) {
                    switch(Orientation) {
                        case 6: //需要顺时针（向左）90度旋转
                            this.rotateImg(img, 'left', canvas);
                            break;
                        case 8: //需要逆时针（向右）90度旋转
                            this.rotateImg(img, 'right', canvas);
                            break;
                        case 3: //需要180度旋转
                            this.rotateImg(img, 'right', canvas); //转两次
                            this.rotateImg(img, 'right', canvas);
                            break;
                    }
                }
                //进行最小压缩
                let ndata = canvas.toDataURL('image/jpeg', 0.6);
                /*console.log('压缩前：' + initSize);
                console.log('压缩后：' + ndata.length);
                console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");*/
                tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
                console.log(this.dataURLtoFile(ndata, 'aaa'))
                var params = new FormData()
                params.append('attachment', this.dataURLtoFile(ndata, 'aaa'))
                this.attach(params)
                return ndata;
            },
            /*图片压缩*/
            dataURLtoFile(dataurl, filename) {
                let arr = dataurl.split(',')
                let mime = arr[0].match(/:(.*?);/)[1]
                let suffix = mime.split('/')[1]
                let bstr = atob(arr[1])
                let n = bstr.length
                let u8arr = new Uint8Array(n)
                while(n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], `${filename}.${suffix}`, {
                    type: mime
                })
            },
            /*上传接口*/
            attach(params) {

                var config = {
                    onUploadProgress: progressEvent => {
                        var complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
                        this.progress = complete
                    }
                }
                this.$post('/member/upload/image', params, config)
                    .then((res) => {
                        this.isloading = false
                        this.images.push(res.data.key)
                    })
                    .catch((error) => {
                        this.isloading = false
                        this.$toast({
                            "message": this.$error[error.response.data.code],
                            'duration': 500
                        })
                    })
            },
            /*删除图片*/
            updelete(e) {
                
                this.isloading = false
                if(this.images.length == 1) {
                    this.images = []
                } else {
                    for(var i = 0; i < this.fileList.length; i++) {
                        if(this.fileList[i].file.name == e.file.name) {
                            if(this.images.length > 0) {
                                this.images.splice(i, 1)
                            }
                        }
                    }
                }
                return true
            },
            /*发布*/
            onClickRight() {
                if(this.desc == '' || this.desc == null || this.desc == undefined) {
                    this.$toast({
                        "message": '请填写内容',
                        'duration': 500
                    });
                } else {
                    if(!this.isloading) {
                        if(this.istrue) {                           
                            this.istrue = false 
                            /*处理换行*/
                           var text = this.desc.replace(/^\s+|\s+$/g,''); 
                           var des = text.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' '); //转换格式
                           
                           console.log(text)
                            this.$post('member/community/message', {
                                    "content": des,
                                    "images_list": this.images
                                })
                                .then((res) => {
                                    this.$toast({
                                        "message": '成功',
                                        'duration': 500
                                    });
                                    this.desc=''
                                    //                          this.$router.go(-1)                            
                                    this.istrue = true
                                    var ua = navigator.userAgent.toLowerCase();
                                    if(/iphone|ipad|ipod/.test(ua)) {
                                        window.webkit.messageHandlers.onBack.postMessage('');
                                    } else if(/android/.test(ua)) {
                                        if((typeof jsObj) != "undefined") {
                                            jsObj.onBack()
                                        } else {

                                        }
                                    } else {
                                        this.$router.go(-1)
                                    }
                                })
                                .catch((error) => {
                                    this.istrue = true
                                    this.$toast({
                                        "message": this.$error[error.response.data.code],
                                        'duration': 800
                                    })
                                })
                        }
                    } else {
                        this.$toast({
                            "message": '图片未上传完成',
                            'duration': 800
                        })
                    }
                }
            },  
            descInput(e) {          	
                var text = this.desc; 
                
                var des = text.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' '); //转换格式
                var txtVal = des.length;
                
                if(txtVal > '300') {
                    this.$toast({
                        "message": '字数最多为300字',
                        'duration': 800
                    })
                    this.remnant = 0
                    this.desc = des.slice(0, 299)
                } else {
                    this.remnant = 300 - txtVal;
                }

            }
        },
        /*设置缓存*/
        beforeRouteLeave(to, from, next) {
            if(to.name == 'home') {
                to.meta.keepAlive = false
            } else {
                to.meta.keepAlive = false
            }
            next()
        },

    }
</script>
<style type="text/css">
    .van-icon,
    .van-icon {}
    
    .van-progress {
        margin-top: 0.0625rem;
    }
    
    .imgPreview {
        width: 70px;
        height: 70px;
    }
    /*.van-uploader__upload{
        background: url(../img/banck2x.png) no-repeat center center;
        background-size:0.625rem 0.625rem ;
    }*/
    
    .van-uploader__preview-delete {
        background: url(../img/dell3@2x.png) no-repeat center center;
        background-size: 0.625rem 0.625rem;
    }
    
    .van-uploader__upload-icon {}
    
    .van-uploader__wrapper {
        /*display: flex;
	    justify-content: space-between;*/
        width: 100%;
    }
    
    .van-uploader__preview-image {
        width: 6.25rem;
        height: 6.25rem;
        position: relative;
    }
    
    .van-uploader__upload {
        width: 6.25rem;
        height: 6.25rem;
    }
</style>
<style scoped="">
    .back {
        position: fixed;
        left: 50%;
        margin-left: -0.625rem;
    }
    
    .van-circle {
        position: fixed;
        top: 50%;
        left: 50%;
        margin-left: -30px;
    }
    
    .van-row {
        margin-top: 0.625rem;
        display: flex;
        justify-content: space-between;
        padding: 0rem 0.625rem;
    }
    
    .van-uploader {
        width: 100%;
    }
    
    .xianzhi {
        position: absolute;
        bottom: 0.9375rem;
        right: 1.5625rem;
        color: rgba(197, 199, 210, 1);
        font-size: 0.75rem;
    }
    
    .publi {
        padding: 0.625rem;
        position: relative;
    }
    
    .publit {
        padding: 0.625rem;
        display: flex;
        justify-content: space-between;
    }
    
    .text {
        width: 100%;
        min-height: 10.1875rem;
        border: 0.03125rem solid #F5F5F5;
        color: rgba(88, 88, 103, 1);
        font-size: 0.8125rem;
        padding: 0.3125rem;
        border-radius: 0.3125rem;
    }
    
    .van-nav-bar {
        /*background: linear-gradient(blue, pink);*/
        /*background: linear-gradient(to right,rgba(34, 82, 232, 1),rgba(227, 76, 230, 1))*/
    }
    
    .van-nav-bar__left {
        width: 3.125rem;
        height: 3.125rem;
        color: #fff;
        background: url(../img/left@2x.png) no-repeat left center;
        background-size: 0.625rem 1.125rem;
    }
    
    .van-nav-bar__text {
        color: #666;
    }
</style>